package rpc_1.Client;

import rpc_1.object.RpcRequest;
import rpc_1.object.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClientProxy implements InvocationHandler {
     private String host;
     private int port;

    public RpcClientProxy(String host,int port){
        this.host=host;
        this.port=port;
    }


    @SuppressWarnings("unchecked")
    public <T> T getProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(),new Class<?>[]{clazz},this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //通过传来的参数，构造一个rpcRequest对象
        RpcRequest rpcRequest=new RpcRequest(method.getDeclaringClass().getName(),
                method.getName(), args, method.getParameterTypes());
        RpcClient rpcClient=new RpcClient();
        //调用sendRequest方法，把rpcRequest通过socket发送给服务端，并等待结果
        RpcResponse o = (RpcResponse)rpcClient.sendRequest(rpcRequest, host, port);
        //拿到结果，返回
        return o.getStatusCode()+"\n"+o.getMessage()+"\n"+o.getData();

    }
}
